/**
 * @name: permission.ts
 * @author: XU>.<CHEN
 * @date: 2022-03-01 21:53
 * @description：路由许可配置
 * @update: 2022-03-01 21:53
 */
import router, {resetRouter} from '@/router'
import { getToken } from '@/utils/auth'
import store from '@/store'

const whiteList = ['/login', '/index', '/', '/404']

interface MenuVo {
  id: string,
  pid: string,
  menuName: string,
  menuPath: string,
  componentPath: string,
  link: string,
  remark: string,
}

router.beforeEach(async(to, from, next) => {
  const token = getToken()
  // case1: 已登陆还输入了登录页 则重定向至首页
  if (token && to.path === '/login') {
    next('/')
    return
  }
  // case2: 未登录 放行白名单
  if (!token) {
    whiteList.indexOf(to.path) !== -1 ? next() : next(`/login?redirect=${to.path}`)
    return
  }

  /**
   * @description: 已登陆
   */
  if (token) {
    const dynamicCreateRoute = store.state.core.dynamicCreateRoute // 异步创建路由标识避免重复请求
    // TODO: 处理所有页面权限 包括404页面等
    if (!dynamicCreateRoute) {
      store.commit('core/updateDynamicCreateRoute', true)
      // 获取登录者拥有的菜单权限 routeAuth
      await store.dispatch('user/getCurrent')
      await store.dispatch('core/getRouteAuth')
      const routeAuth = store.state.core.routeAuth
      console.log(routeAuth)
      if (routeAuth.length === 0) {
        next('/')
        return
      }
      routeAuth.forEach((menu: MenuVo) => {
        const routeOne: any = {
          path: menu.menuPath,
          name: menu.menuName,
          component: () => import(`./views${menu.componentPath}`)
        }
        if (!router.hasRoute(menu.menuName)) router.addRoute('home', routeOne) // 插入菜单权限
      })
      // 递归调用{ ...to, replace: true } 由于刷新页面的时候动态路由会刷新掉，然后动态路由会重新加载，而匹配路由会在加载路由之前，所以会导致空白页
      next({ ...to, replace: true })
    } else {
      next()
    }
  }
  // 必须有 否则访问不存在路由不会跳转404
  if (!router.hasRoute('redirect404')) router.addRoute({path: '/:catchAll(.*)', name: 'redirect404', redirect: '/404'})
})
